package com.naver.geojson;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;

import javax.imageio.ImageIO;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class GeojsonReader {
	private static final String CHARSET = "UTF-8";

	public static void main(String[] args) throws Exception {
		byte[] output = readIt();
		System.out.println("end");
		BufferedImage bi = ImageIO.read(new URL("http://onetile4.map.naver.net/get/25/0/0/11/1709/1438/bl_vc_bg").openStream());
		ImageIO.write(bi, "jpg", new File("d:/tmp/output.jpg"));
	}
	
	public static byte[] readIt() throws Exception {
		int level = 9;
		final String url = "http://dev.search.map.naver.com:10118/picker?request=polygonToFeatures&version=1.3&sourcecrs=NHN:2048&order=detail&output=json&coords=965120.000%2c1927616.000%7c965376.000%2c1927872.000&level=12&targetcrs=NHN:2048";
		InputStreamReader inputStreamReader = new InputStreamReader(new URL(url).openStream(), CHARSET);
		JsonReader json = new JsonReader(inputStreamReader);
		Gson gson = new Gson();
		FeatureCollection collection = gson.fromJson(json, FeatureCollection.class);
		
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
		
		for (Feature feature : collection.features) {
			System.out.println("------------------------------------");
			System.out.println(feature.geometry.coordinates);
			System.out.println(feature.properties.mID);
			System.out.println(feature.properties.name);
			System.out.println(feature.properties.angle);
			System.out.println(feature.properties.pid_code);
			System.out.println("------------------------------------");
			
			dataOutputStream.writeInt(feature.properties.name.length());
			dataOutputStream.writeBytes(feature.properties.name);
			dataOutputStream.writeInt(feature.properties.pid_code);
			dataOutputStream.writeInt(level);
			dataOutputStream.writeInt(feature.properties.angle);
		}
		
		dataOutputStream.close();

		return byteArrayOutputStream.toByteArray();
	}
}
